<route lang="json5">
{
  style: {
    navigationBarTitleText: '编辑用户信息',
  },
}
</route>

<template>
  <view class="root-container">
    <view class="page-container">
      <gi-form ref="formRef" v-model="formData" :columns="formColumns">
        <!--        <template #deptId> -->
        <!--          <sar-tree -->
        <!--            :data="deptList" -->
        <!--            selectable -->
        <!--            check-strictly -->
        <!--          /> -->
        <!--        </template> -->
      </gi-form>

      <view class="form-actions">
        <sar-button theme="primary" @click="handleCancel">取消</sar-button>
        <sar-button theme="success" @click="handleSubmit">保存</sar-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import type { UserReq } from '@/apis/system/type'
import type { ColumnItem, GiFormInstance } from '@/components/gi-form/type'
import { updateUser } from '@/apis/system/user'
import { GenderList } from '@/constant/common'
import { useDept } from '@/hooks/useDept'
import { useRole } from '@/hooks/useRole'
import { useUserStore } from '@/store'

defineOptions({
  inheritAttrs: false,
})
const userStore = useUserStore()
const formRef = ref<GiFormInstance>()
// 表单数据
const formData = reactive<Partial<UserReq>>({
  username: '',
  nickname: '',
  roleIds: [],
})

// 部门选项
const { getDeptList } = useDept()

// 角色选项
const { roleList, getRoleList } = useRole()

// 表单列配置
const formColumns = computed(() => [
  {
    type: 'input',
    label: '用户名',
    field: 'username',
    rules: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { pattern: /^[a-z]\w{3,63}$/i, message: '用户名长度为 4-64 个字符，支持大小写字母、数字、下划线，以字母开头', trigger: 'blur' },
    ],
  },
  {
    type: 'input',
    label: '昵称',
    field: 'nickname',
    rules: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
      { pattern: /^[\u4E00-\u9FA5\w-]{2,30}$/, message: '昵称长度为 2-30 个字符，支持中文、字母、数字、下划线，短横线', trigger: 'blur' },
    ],
  },
  {
    type: 'input',
    label: '邮箱',
    field: 'email',
    rules: [
      { pattern: /^[\w.%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i, message: '邮箱格式不正确', trigger: 'blur' },
    ],
  },
  {
    type: 'input',
    label: '手机号',
    field: 'phone',
    rules: [
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
    ],
  },
  {
    type: 'radio-group',
    label: '性别',
    field: 'gender',
    rules: [
      { required: true, message: '请选择性别', trigger: 'change' },
    ],
    props: {
      direction: 'horizontal',
      options: GenderList,
    },
  },
  // {
  //   label: '所属部门',
  //   field: 'deptId',
  //   rules: [
  //     { required: true, message: '请选择所属部门', trigger: 'change' },
  //   ],
  //   slotName: 'deptId',
  // },
  {
    type: 'picker',
    label: '所属角色',
    field: 'roleIds',
    rules: [
      { required: true, message: '请选择所属角色', trigger: 'blur' },
    ],
    props: {
      columns: roleList.value,
      multiple: true,
    },
  },
  {
    type: 'textarea',
    label: '描述',
    field: 'description',
    rules: [
      { max: 200, message: '描述长度不能超过 200 个字符', trigger: 'blur' },
    ],
  },
] as ColumnItem[])

// 初始化数据
onLoad(async () => {
  try {
    // 获取部门列表
    await getDeptList()
    // 获取角色列表
    await getRoleList()

    // 获取用户信息
    const userInfo = userStore.userInfo
    if (userInfo) {
      formData.username = userInfo.username || ''
      formData.nickname = userInfo.nickname || ''
      formData.email = userInfo.email || ''
      formData.phone = userInfo.phone || ''
      formData.gender = userInfo.gender
      formData.deptId = userInfo.deptId || 0
      formData.roleIds = userInfo.roleIds || []
      formData.description = userInfo.description || ''
      formData.status = userInfo.status
    }
  }
  catch (error) {
    console.error('初始化数据失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none',
    })
  }
})

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value?.formRef.validate()
    const userId = userStore.userInfo?.id
    if (!userId) {
      uni.showToast({
        title: '用户ID不存在',
        icon: 'none',
      })
      return
    }

    // 确保必选字段存在
    if (!formData.username || !formData.nickname || formData.gender === undefined || !formData.deptId || !formData.roleIds) {
      uni.showToast({
        title: '请填写必填信息',
        icon: 'none',
      })
      return
    }

    // 调用更新用户接口
    const res = await updateUser(formData as UserReq, userId)
    if (res.success) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
      })
      // 更新本地用户信息
      userStore.updateUserInfo(formData as UserReq)
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
    else {
      uni.showToast({
        title: res.msg || '保存失败',
        icon: 'none',
      })
    }
  }
  catch (error) {
    console.error('表单验证失败', error)
  }
}

// 取消
function handleCancel() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.root-container {
  width: 100%;
  height: 100%;
}

.page-container {
  padding: 20px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 20px;
}
</style>
